﻿#define _CRT_SECURE_NO_WARNINGS 1
#include "List.h"

//打印
void SLTPrint(SLTNode* phead)
{
	SLTNode* prve = phead;
	while (prve)
	{
		printf("%d->", prve->data);
		prve = prve->next;
	}
	printf("NULL\n");
}


//扩容
SLTNode* Expansion(SLTDataType x)
{
	SLTNode* node = (SLTNode*)malloc(sizeof(SLTNode));
	if (node==NULL)
	{
		perror("malloc!");
		exit(1);
	}
	else
	{
		node->data = x;
		node->next = NULL;
	}
	return node;
}

//尾部插⼊
void SLTPushBack(SLTNode** pphead, SLTDataType x)
{
	SLTNode* newnode = Expansion(x);
	if (*pphead==NULL)
	{
		*pphead = newnode;
	}
	else
	{
		SLTNode* prve = *pphead;
		while (prve->next)
		{
			prve = prve->next;
		}
		prve->next = newnode;
	}
}

//头部插⼊
void SLTPushFront(SLTNode** pphead, SLTDataType x)
{
	SLTNode* newnode = Expansion(x);
	//SLTNode* prve = *pphead;
	newnode->next = *pphead;
	*pphead = newnode;
}

//尾部删除
void SLTPopBack(SLTNode** pphead)
{
	assert(pphead && *pphead);
	if ((*pphead)->next == NULL)
	{
		free(*pphead);
		*pphead = NULL;
	}
	else
	{
		SLTNode* prve = *pphead;
		SLTNode* tail = NULL;
		while (prve->next)
		{
			tail = prve;
			prve = prve->next;
		}
		tail->next = NULL;
		free(prve);
		prve = NULL;
	}
}

//头部删除
void SLTPopFront(SLTNode** pphead)
{
	SLTNode* prve = (*pphead)->next;
	free(*pphead);
	*pphead = prve;
}

//查找
SLTNode* SLTFind(SLTNode* phead, SLTDataType x)
{
	assert(phead);
	SLTNode* prve = phead;
	while (prve)
	{
		if (prve->data == x)
		{
			return prve;
		}
		prve = prve->next;
	}
	return NULL;
}

//在指定位置之前插⼊数据
void SLTInsert(SLTNode** pphead, SLTNode* pos, SLTDataType x)
{
	assert(pphead);
	assert(pos);
	if (*pphead==pos)
	{
		SLTPushFront(pphead, x);
	}
	else
	{
		SLTNode* newnode = Expansion(x);
		SLTNode* prev = *pphead;
		while (prev->next != pos)
		{
			prev = prev->next;
		}
		prev->next = newnode;
		newnode->next = pos;
	}
}

//在指定位置之后插⼊数据
void SLTInsertAfter(SLTNode* pos, SLTDataType x)
{
	assert(pos);
	SLTNode* newnode = Expansion(x);
	newnode->next = pos->next;
	pos->next = newnode;
}

//删除pos结点
void SLTErase(SLTNode** pphead, SLTNode* pos)
{
	assert(pphead);
	assert(pos);
	if (*pphead==NULL)
	{
		free(*pphead);
		*pphead = NULL;
	}
	else
	{
		SLTNode* prve = *pphead;
		while (prve->next != pos)
		{
			prve = prve->next;
		}
		prve->next = pos->next;
		free(pos);
		pos = NULL;
	}
}

//删除pos之后的结点
void SLTEraseAfter(SLTNode* pos)
{
	assert(pos);
	SLTNode* next = pos->next;
	pos->next = pos->next->next;
	free(next);
	next = NULL;
}

//销毁链表
void SListDestroy(SLTNode** pphead)
{
	assert(pphead);
	if (*pphead==NULL)
	{
		free(*pphead);
		*pphead = NULL;
	}
	else
	{
		SLTNode* prve = *pphead;
		while (prve)
		{
			SLTNode* next = prve->next;
			free(prve);
			prve = next;
		}
		*pphead = NULL;
	}
}